#!/bin/bash

# 构建Docker镜像并推送到镜像仓库
# 在开发机器上运行，构建好镜像后推送到Docker Hub或私有仓库
# 服务器上只需要拉取镜像，无需源码

set -e

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

info() { echo -e "${GREEN}[INFO]${NC} $1"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; }

# 配置
IMAGE_REGISTRY="${IMAGE_REGISTRY:-docker.io}"  # 可以改为私有仓库地址
IMAGE_NAMESPACE="${IMAGE_NAMESPACE:-your-namespace}"  # 改为你的Docker Hub用户名或组织名
IMAGE_TAG="${IMAGE_TAG:-latest}"

BACKEND_IMAGE="${IMAGE_REGISTRY}/${IMAGE_NAMESPACE}/aps-backend:${IMAGE_TAG}"
FRONTEND_IMAGE="${IMAGE_REGISTRY}/${IMAGE_NAMESPACE}/aps-frontend:${IMAGE_TAG}"

echo "=========================================="
echo "  构建并推送APS Docker镜像"
echo "=========================================="
echo ""
info "后端镜像: ${BACKEND_IMAGE}"
info "前端镜像: ${FRONTEND_IMAGE}"
echo ""

# 检查是否在项目根目录
if [ ! -f "pom.xml" ]; then
    error "请在项目根目录运行此脚本"
    exit 1
fi

# 构建后端镜像
info "构建后端镜像..."
docker build -t ${BACKEND_IMAGE} -f Dockerfile.backend .

# 构建前端镜像
info "构建前端镜像..."
docker build -t ${FRONTEND_IMAGE} -f ui/Dockerfile ui/

# 推送镜像
read -p "是否推送镜像到仓库? (y/n): " push_confirm
if [ "$push_confirm" == "y" ]; then
    info "推送后端镜像..."
    docker push ${BACKEND_IMAGE}
    
    info "推送前端镜像..."
    docker push ${FRONTEND_IMAGE}
    
    echo ""
    echo "=========================================="
    echo -e "${GREEN}镜像构建并推送成功！${NC}"
    echo "=========================================="
    echo ""
    info "在服务器上使用以下镜像："
    echo "  后端: ${BACKEND_IMAGE}"
    echo "  前端: ${FRONTEND_IMAGE}"
    echo ""
    info "更新 deployment/docker-compose.yml 中的镜像地址"
else
    echo ""
    info "镜像已构建，但未推送"
    info "本地镜像："
    echo "  后端: ${BACKEND_IMAGE}"
    echo "  前端: ${FRONTEND_IMAGE}"
fi

